const { Router } = require('express')

const sexpage = require('mongoose-sex-page')

const { Article } = require('../model/Article')
const { Comment } = require('../model/Comment')

// 创建路由
const router = Router();

// 首页
router.get('/', async (req, res) => {
    const { page = 1 } = req.query;
    const data = await sexpage(Article)
        .page(page)
        .size(2)
        .display(5)
        .find()
        .populate('author')
        .exec()
    res.render('home/index', data);
});

router.get('/article/:id', async (req, res) => {
    const { id } = req.params;
    const article = await Article.findOne({ _id: id }).populate('author');
    const comment = await Comment.find({ article: id }).populate('user');
    res.render('home/article', { article, comments: comment })
});

router.post('/article/:aid/comment', async (req, res) => {
    const { aid } = req.params;
    const { uid, content } = req.body;

    await Comment.create({
        article: aid,
        user: uid,
        content
    })
    res.redirect(`/home/article/${aid}`);
});

// 导出路由
module.exports = { router };